import {
  uploadFile,
  mergeChunks,
  uploadFilePre,
  uploadRadarFile,
  mergeRadarChunks,
  uploadRadarFilePre,
} from './upload'
import { getFileChunk, DefaultChunkSize } from './chunk'
import { fileChunkList, fileHash, setFileHash, clearFileHash } from './file'

export const upload = async (file, updateProcess, params) => {
  let chunkList = null
  if (!fileHash) {
    setFileHash(await getFileChunk(file, params))
    chunkList = fileChunkList.value
  } else {
    const rsp = await uploadFilePre({ md5: fileHash })
    if (rsp.data && rsp.data.length > 0) {
      const existArr = rsp.data.map(item => parseInt(item))
      const indexSet = new Set(existArr)
      chunkList = fileChunkList.value.filter((_, index) => !indexSet.has(index))
    }
  }
  const requests = chunkList.map((item, index) => {
    const formData = new FormData()
    formData.append('file', item.chunk)
    formData.append('num', item.num)
    formData.append('sum', fileChunkList.value.length)
    formData.append('md5', fileHash)
    return uploadFile(formData, updateProcess(item))
  })
  await Promise.all(requests)
  const formData = new FormData()
  formData.append('fileName', file.name)
  formData.append('md5', fileHash)
  await mergeChunks(formData, params)
  fileChunkList.value = []
  clearFileHash(true)
}
export const uploadRadar = async (file, updateProcess, params) => {
  let chunkList = null
  if (!fileHash) {
    setFileHash(await getFileChunk(file, params))
    chunkList = fileChunkList.value
  } else {
    const rsp = await uploadRadarFilePre({ md5: fileHash })
    if (rsp.data && rsp.data.length > 0) {
      const existArr = rsp.data.map(item => parseInt(item))
      const indexSet = new Set(existArr)
      chunkList = fileChunkList.value.filter((_, index) => !indexSet.has(index))
    }
  }
  const requests = chunkList.map((item, index) => {
    const formData = new FormData()
    formData.append('file', item.chunk)
    formData.append('num', item.num)
    formData.append('sum', fileChunkList.value.length)
    formData.append('md5', fileHash)
    return uploadRadarFile(formData, updateProcess(item))
  })
  await Promise.all(requests)
  const formData = new FormData()
  formData.append('fileName', file.name)
  formData.append('md5', fileHash)
  await mergeRadarChunks(formData, params)
  fileChunkList.value = []
  clearFileHash(true)
}